<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/5/28
 * Time: 下午6:33
 */

namespace EasySwoole\EasySwoole;


use App\Process\HotReload;
use EasySwoole\Http\Request;
use EasySwoole\Pool\Manager;
use EasySwoole\Http\Response;
use EasySwoole\ORM\DbManager;
use EasySwoole\RedisPool\Redis;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\Redis\Config\RedisClusterConfig;
use EasySwoole\EasySwoole\AbstractInterface\Event;

class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        date_default_timezone_set('Asia/Shanghai');
        self::dbRegister();
        self::redisPool();
    }

    public static function mainServerCreate(EventRegister $register)
    {
        self::hotReload();
    }

    public static function dbRegister()
    {
        $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
        DbManager::getInstance()->addConnection(new Connection($config));
    }

    public static function redisPool() {
        $config = Config::getInstance()->getConf('REDIS');
        $redisPoolConfig = Redis::getInstance()->register('redis',new RedisConfig($config));
        $redisPoolConfig->setMinObjectNum($config['POOL_MIN_NUM'] ?? 5);
        $redisPoolConfig->setMaxObjectNum($config['POOL_MAX_NUM'] ?? 20);

        $clusterConfig = Config::getInstance()->getConf('REDISCLUSTER');

        if($clusterConfig) {
            Redis::getInstance()->register('redisCluster',new RedisClusterConfig($clusterConfig));
        }
    }

    public static function hotReload()
    {
        $swooleServer = ServerManager::getInstance()->getSwooleServer();
        $swooleServer->addProcess((new HotReload('HotReload', ['disableInotify' => false]))->getProcess());
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}